const orderModel = require('../models/orderModel');
const userModel = require('../models/userModel');
const merchantService = require('../service/merchantService');
const goodsService = require('../service/goodsService');
const integralService = require('../service/integralService');
const pushUtils = require('../utils/push');
const wxPush = require('../utils/wxPush');
const utils = require('../utils/util');
const create = async(ctx, next) => {
    try {
        const req = ctx.request.body;
		const curUserId = ctx.state.user.userId;
        const data = Object.assign({
            status: 1,
            createDate: new Date(),
            createUser: curUserId
        }, req);
		data.orderNo = utils.generateOrderNo();
		const curUser = await userModel.findById(curUserId);
		let integralAmount = 0;
		let userIntegral = 0;
		if (req.integralDeduction) {
			// 开启了积分抵扣
			userIntegral = curUser.integral;
			if (userIntegral > 10) {
				integralAmount = userIntegral / 10;
			}
		}
        let goodsDetails = {};
        req.detail.filter(item => goodsDetails[item.goodsId] = item.skuId);
        const goodsIds = Object.keys(goodsDetails);
        const dbGoods = await goodsService.findByIds(goodsIds);
        let goodsId = '';
        let skuId = '';
        let sku = null;
        let detail = null;
        let totalOriginalPrice = 0;
        let totalDiscountPrice = 0;
        data.detail = [];
        for (let goods of dbGoods) {
            goodsId = goods._id;
            skuId = goodsDetails[goodsId];
            detail = req.detail.filter(item => item.goodsId == goodsId)[0];
            sku = goods.skuList.filter(item => item._id == skuId)[0];
            // 校验库存
            if (sku.repertory < detail.count) {
                throw new Error(`${goods.name}库存不足`);
            }
            totalOriginalPrice += sku.originalPrice * detail.count;
            totalDiscountPrice += (sku.discountPrice || sku.originalPrice) * detail.count;
            data.detail.push({
                goodsId,
                goodsName: goods.name,
                thumbnail: goods.thumbnail,
                skuId: goodsDetails[goodsId],
                skuName: sku.name,
                originalPrice: sku.originalPrice,
                discountPrice: sku.discountPrice,
                count: detail.count
            });
        }
        data.originalPrice = totalOriginalPrice;
        data.discountPrice = totalDiscountPrice;
		data.actualPrice = totalDiscountPrice - integralAmount;
		const merchants = await merchantService.findById(data.merchantId);
		if (totalDiscountPrice < merchants.minDeliveryAmount) {
			// 订单金额小于起送价
			return ctx.body = {
			    code: -1,
			    msg: `满${merchants.minDeliveryAmount}元才能配送呦！`
			}
		}
        const goods = req.detail;

        for (const item of goods) {
            await goodsService.updRepertory({ id: item.goodsId, skuId: item.skuId, count: item.count });
        }
        await orderModel.create(data);
		if (req.integralDeduction && integralAmount) {
			integralService.create({
				orderId: data._id,
				orderNo: data.orderNo,
				userId: curUserId,
				value: userIntegral,
				type: 2
			});
		} 
		const curIntegral = Math.floor(data.actualPrice);
		integralService.create({
			orderId: data._id,
			orderNo: data.orderNo,
			userId: curUserId,
			value: curIntegral,
			type: 1
		});
		curUser.integral += curIntegral;
		userModel.update({
		    _id: curUserId
		}, curUser);
        await pushUtils.batchPush(merchants.owners, {
            title: '您有新的订单',
            body: '赶快去处理吧'
        })
        ctx.body = {
            code: 1,
            msg: '操作成功！'
        }
    } catch (e) {
		console.log(e);
        return ctx.body = {
            code: -1,
            msg: e.message,
            data: {}
        };
    }
}

const findByUserId = async(ctx, next) => {
    const userId = ctx.state.user.userId;
    const condition = {
        createUser: userId
    };
    const status = ctx.request.query.status;
    if (status) {
        condition.status = status;
    }
    const result = await orderModel.find(condition);
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const findByMerchantId = async(ctx, next) => {
	const {merchantId, status} = ctx.query;
    const result = await orderModel.find({
        merchantId,
		status
    });
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const findCountByMerchantId = async(ctx, next) => {
	const {merchantId} = ctx.query;
    const confirmResult = await orderModel.find({
        merchantId,
		status: 1
    }, {id: 1});
	const goingResult = await orderModel.find({
	    merchantId,
		status: 2
	}, {id: 1});
	const finashedResult = await orderModel.find({
	    merchantId,
		status: 3
	}, {id: 1});
    ctx.body = {
        code: 1,
        data: {
    		confirm: confirmResult.length,
    		going: goingResult.length,
    		finashed: finashedResult.length
    	}
    };
}

const findTodyByMerchantId = async(ctx, next) => {
	const {merchantId} = ctx.query;
	const day1 = new Date();
	day1.setTime(day1.getTime()-24*60*60*1000);
	const yesterDate = day1.getFullYear()+"/" + (day1.getMonth()+1) + "/" + day1.getDate();
	const result = await orderModel.find({
	    merchantId,
		status: {$gt: -1},
		createDate: {$gte: yesterDate}
	}, {id: 1, actualPrice: 1});
	let money = 0;
	result.forEach(item => money += item.actualPrice);
    ctx.body = {
        code: 1,
        data: {
    		total: result.length,
    		money
    	}
    };
}

const findById = async(ctx, next) => {
    const id = ctx.query.id;
    const result = await orderModel.findById(id);
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const find = async(ctx, next) => {
    const query = ctx.request.query;
    const name = query.name;
    const classify = query.classify;
    const condition = {
        status: 1
    };
    if (name) {
        condition.name = {
            $regex: name
        }
    }
    if (classify) {
        condition['classify.id'] = classify
    }
    const result = await orderModel.find(condition, null, {
        sort: {
            createDate: 'desc'
        }
    });
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const operation = async(ctx, next) => {
	const {id, status} = ctx.query;
    const result = await orderModel.update({
        _id: id
    }, {status});
    if (result) {
		const detail = await orderModel.findById(id);
		const user = await userModel.findById(detail.createUser);
		if (status == 2) {
			// 下单成功
			wxPush.createOrderSubmitMessage({
				openId: user.openId, 
				orderNo: detail.orderNo,
				goods: detail.detail, 
				amount: detail.actualPrice
			});
		} else if (status == 3) {
			// 订单已完成
			wxPush.createOrderFinashedMessage({
				openId: user.openId, 
				orderNo: detail.orderNo,
				goods: detail.detail, 
				amount: detail.actualPrice
			});
		}
		
        ctx.body = {
            code: 1,
            msg: '修改成功！',
            data: {}
        };
    }
}

const update = async(ctx, next) => {
    const req = ctx.request.body;
    const result = await orderModel.update({
        _id: req._id
    }, req);
    if (result) {
        ctx.body = {
            code: 1,
            msg: '修改成功！',
            data: {}
        };
    }
}

module.exports = {
    create,
    find,
    update,
    findById,
    findByUserId,
    findByMerchantId,
	operation,
	findCountByMerchantId,
	findTodyByMerchantId
};